<template>
  <div class="product-admin">
    <h2>🛒 <span>商品管理</span></h2>
    <div class="product-list">
      <table v-if="products.length" class="product-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>名称</th>
            <th>描述</th>
            <th>价格</th>
            <th>图片</th>
            <th>库存</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in products" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.descriptions }}</td>
            <td style="color: #e63946; font-weight: bold">¥{{ item.price }}</td>
            <td><img :src="item.img" alt="商品图片" style="width: 60px; height: 40px; object-fit: cover;" /></td>
            <td style="color: #e63946; font-weight: bold">{{ item.numbers }}</td>
            <td>
              <button @click="editProduct(item)">编辑</button>
              <button @click="deleteProductItem(item.id)">下架</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-else style="margin: 32px 0; color: #888;">暂无商品</div>
    </div>
    <button class="q-btn" @click="openAddModal">添加商品</button>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showModal" class="modal-mask">
      <div class="modal-content q-modal">
        <h3 class="q-title">🛒 {{ editId ? '编辑商品' : '添加商品' }}</h3>
        <form @submit.prevent="submitProduct" class="form-grid q-form">
          <div class="form-row">
            <div class="form-item">
              <label>✨ 名称</label>
              <input v-model="form.name" required />
            </div>
            <div class="form-item">
              <label>📝 描述</label>
              <input v-model="form.descriptions" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <label>💰 价格</label>
              <input v-model.number="form.price" type="number" step="0.01" min="0" required placeholder="请输入商品价格，可为小数" />
            </div>
            <div class="form-item">
              <label>📦 库存</label>
              <input v-model.number="form.numbers" type="number" required />
            </div>
          </div>
          <!-- <div class="form-row">
            <div class="form-item">
              <label>🔍 详细描述</label>
              <input v-model="form.descriptionsInfo" />
            </div>
            <div class="form-item" style="visibility:hidden;"></div>
          </div> -->
          <div class="form-row">
            <div class="form-item" style="width:100%;">
              <label>🖼️ 图片</label>
              <div class="q-upload">
                <input type="file" accept="image/*" @change="handleImageUpload" />
                <div v-if="form.img" class="img-preview">
                  <img :src="form.img" alt="图片预览" />
                  <div class="img-filename">{{ getFileName(form.img) }}</div>
                </div>
                <div v-else class="img-preview-placeholder">
                  <span style="font-size:2.2rem;">🦄</span>
                  <div style="color:#bbb;font-size:0.95rem;">暂无图片</div>
                </div>
              </div>
            </div>
          </div>
          <div class="form-actions q-actions">
            <button type="button" @click="closeModal">取消</button>
            <button type="submit">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getProductList, addProduct, deleteProduct, updateProduct } from '../../api/product'

const products = ref<any[]>([])
const showModal = ref(false)
const editId = ref<number|null>(null)
const form = ref({
  name: '',
  descriptions: '',
  price: 0,
  img: '',
  numbers: 0,
  descriptionsInfo: ''
})
const pageNo = ref(1)
const pageSize = ref(20)

async function loadProducts() {
  const res = await getProductList({ pageNo: pageNo.value, pageSize: pageSize.value })
  if (res && res.data) {
    products.value = Array.isArray(res.data) ? res.data : (res.data.records || [])
  }
}

onMounted(loadProducts)

function openAddModal() {
  editId.value = null
  form.value = { name: '', descriptions: '', price: 0, img: '', numbers: 0, descriptionsInfo: '' }
  showModal.value = true
}

function closeModal() {
  showModal.value = false
}

async function submitProduct() {
  if (editId.value) {
    await updateProduct({ ...form.value, id: editId.value })
  } else {
    await addProduct(form.value)
  }
  showModal.value = false
  await loadProducts()
}

function editProduct(item: any) {
  editId.value = item.id
  form.value = {
    name: item.name,
    descriptions: item.descriptions,
    price: item.price,
    img: item.img,
    numbers: item.numbers,
    descriptionsInfo: item.descriptionsInfo || ''
  }
  showModal.value = true
}

async function deleteProductItem(id: number) {
  if (confirm('确定要下架该商品吗？')) {
    await deleteProduct(id)
    await loadProducts()
  }
}

// 上传图片到图片服务器
async function handleImageUpload(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  const formData = new FormData()
  formData.append('file', file)
  try {
    const resp = await fetch('http://120.55.114.213:9090/group1/upload', {
      method: 'POST',
      body: formData
    })
    let text = await resp.text();
    let url = '';
    try {
      // 尝试解析为JSON
      const result = JSON.parse(text);
      url = result?.data?.url ? String(result.data.url).replace(/\s/g, '') : '';
      let fallbackUrl = (result?.data?.domain && result?.data?.path)
        ? (String(result.data.domain).replace(/\s/g, '') + String(result.data.path).replace(/\s/g, ''))
        : '';
      if (url && url.includes('/group1/default/')) {
        form.value.img = url;
        return;
      } else if (fallbackUrl && fallbackUrl.includes('/group1/default/')) {
        form.value.img = fallbackUrl;
        return;
      }
    } catch (err) {
      // 不是JSON，直接当作图片链接
      url = text.trim();
      if (url && url.includes('/group1/default/')) {
        form.value.img = url;
        return;
      }
    }
    alert('图片上传失败：图片链接不合法');
    console.log('图片上传失败，内容：', text);
  } catch (err) {
    alert('图片上传失败');
    console.log('图片上传异常:', err);
  }
}

function getFileName(url: string) {
  if (!url) return ''
  try {
    const u = new URL(url)
    const params = u.searchParams.get('name')
    if (params) return params
    return url.split('/').pop()?.split('?')[0] || ''
  } catch {
    return url.split('/').pop()?.split('?')[0] || ''
  }
}
</script>
<style scoped>
.product-admin {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
}
h2 {
  font-size: 2.2rem;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  color: #2563eb;
  margin-bottom: 32px;
  text-shadow: 1px 2px 8px #e3edfa;
  display: flex;
  align-items: center;
  gap: 10px;
}
.product-list {
  width: 100%;
  max-width: 1000px;
  margin-bottom: 32px;
}
.product-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.product-table th, .product-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #f1f5f9;
  text-align: center;
}
.product-table th {
  background: #f8fafc;
  color: #2563eb;
  font-weight: 600;
}
.q-btn {
  margin-top: 24px;
  background: linear-gradient(90deg, #e3edfa 0%, #2563eb 100%);
  color: #fff;
  border: none;
  border-radius: 14px;
  padding: 12px 32px;
  font-size: 1.1rem;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  box-shadow: 0 4px 16px 0 rgba(120, 160, 255, 0.10);
  cursor: pointer;
  transition: background 0.2s, transform 0.2s;
}
.q-btn:hover {
  background: linear-gradient(90deg, #2563eb 0%, #e3edfa 100%);
  color: #2563eb;
  transform: scale(1.04);
}
.modal-mask {
  position: fixed;
  z-index: 1000;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
}
.q-modal {
  background: #fafdff;
  border-radius: 28px;
  padding: 40px 36px;
  min-width: 360px;
  box-shadow: 0 8px 32px 0 rgba(120, 160, 255, 0.18);
  border: 2.5px solid #e3edfa;
}
.q-title {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  font-weight: 700;
  color: #2563eb;
  gap: 8px;
  margin-bottom: 24px;
  letter-spacing: 1px;
}
.q-form {
  display: flex;
  flex-direction: column;
  gap: 0;
}
.form-row {
  display: flex;
  flex-direction: row;
  gap: 24px;
  margin-bottom: 18px;
}
.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.q-form label {
  font-weight: 700;
  color: #2563eb;
  font-size: 1.08rem;
  margin-bottom: 4px;
  letter-spacing: 1px;
}
.q-form input[type='text'],
.q-form input[type='number'] {
  border-radius: 16px;
  border: 1.5px solid #e3edfa;
  padding: 12px 18px;
  font-size: 1.08rem;
  background: #f6faff;
  transition: border 0.2s;
  outline: none;
  margin-bottom: 0;
}
.q-form input:focus {
  border: 1.5px solid #2563eb;
  background: #fff;
}
.q-upload {
  border: 2px dashed #e3edfa;
  border-radius: 16px;
  padding: 16px;
  background: #f6faff;
  display: flex;
  align-items: center;
  gap: 16px;
}
.q-upload input[type='file'] {
  border: none;
  background: none;
}
.img-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.img-preview img {
  max-width: 120px;
  max-height: 80px;
  border-radius: 12px;
  border: 1.5px solid #e3edfa;
  box-shadow: 0 2px 8px rgba(120,160,255,0.08);
}
.img-filename {
  color: #2563eb;
  font-size: 0.98rem;
  margin-top: 2px;
  word-break: break-all;
}
.img-preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 100px;
  min-height: 70px;
  color: #bbb;
  background: #f6faff;
  border-radius: 12px;
  border: 1.5px dashed #e3edfa;
  margin-top: 2px;
}
.q-actions {
  display: flex;
  justify-content: flex-end;
  gap: 18px;
  margin-top: 28px;
}
.q-actions button {
  padding: 12px 32px;
  border-radius: 16px;
  border: none;
  font-size: 1.1rem;
  cursor: pointer;
  background: linear-gradient(90deg, #e3edfa 0%, #2563eb 100%);
  color: #fff;
  font-weight: 700;
  box-shadow: 0 4px 16px 0 rgba(120, 160, 255, 0.10);
  transition: background 0.2s, transform 0.2s;
}
.q-actions button[type='button'] {
  background: #e3edfa;
  color: #2563eb;
}
.q-actions button:hover {
  background: linear-gradient(90deg, #2563eb 0%, #e3edfa 100%);
  color: #2563eb;
  transform: scale(1.06);
}
@media (max-width: 600px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  .q-modal {
    min-width: 90vw;
    padding: 18px 4vw;
  }
}
</style> 